package com.example.demo.Controller;


import jakarta.servlet.http.*;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {

    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName()
            + ":"+ck.getValue()));
        }
        return "获取Cookie";

    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "从Cookie中获取值：bite"+bite;
    }

    //设置Session
    @RequestMapping("/setSession1")
    public String setSession1(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "Session设置成功了";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        //从Cookie中获取到sessionId，根据sessionId来获取Session对象：
        HttpSession session = request.getSession();
        String name = (String)session.getAttribute("name");
        return "从Session中获取到name："+name;
    }

    @RequestMapping("/getSess3")
    public String getSess3(@SessionAttribute("name") String name){
        return "从session中获取name:"+name;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name){
        return "从session中获取name"+name;

    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String UserAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent："+UserAgent;
    }
}
